package com.javaDemo.ti;

/**
 * @ClassName: Xunzhaochongfushu
 * @Auther: csy https://leetcode-cn.com/problems/find-the-duplicate-number/solution/xun-zhao-zhong-fu-shu-by-leetcode-solution/
 * @Date: 2020/12/16 19:24
 * @Description:
 */
public class Xunzhaochongfushu {
    public static void main(String[] args) {
        int[] nums={3,30,34,3,9};
        System.out.println(findDuplicate(nums));
    }
    public static int findDuplicate(int[] nums) {
        int n = nums.length;
        int l = 1, r = n - 1, ans = -1;
        while (l <= r) {
            int mid = (l + r) >> 1;
            int cnt = 0;
            for (int i = 0; i < n; ++i) {
                if (nums[i] <= mid) {
                    cnt++;
                }
            }
            if (cnt <= mid) {
                l = mid + 1;
            } else {
                r = mid - 1;
                ans = mid;
            }
        }
        return ans;
    }
}
